import React, { Fragment, useState } from 'react';

import { Button, Modal, Form, Input, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';

import LinkButton from '../../../components/LinkButton';
import { reqAddCategory } from '../../../api';

const { Item, useForm } = Form;

export default function AddCategory(props) {

    const { path, refresh } = props;

    const [form] = useForm();

    const current = path[path.length - 1];

    const [visible, setVisible] = useState(false);

    return (
        <Fragment>
            <Button type="primary" onClick={() => setVisible(visible => !visible)} icon={<PlusOutlined />} children="添加" />
            <Modal title={setTitle(current)} visible={visible} onOk={() => add(current, form, refresh, setVisible)} onCancel={() => cancel(form, setVisible)}>
                <Form form={form}>
                    <Item
                        name="name"
                        initialValue=""
                        rules={[
                            { required: true, message: '分类名不能为空', whitespace: true }
                        ]}
                    >
                        <Input placeholder="输入分类名" autoComplete="off"></Input>
                    </Item>
                </Form>
            </Modal>
        </Fragment>
    )
}


function add(current, form, refresh, setVisible) {
    form.validateFields()
        .then(async vals => {
            const {name} = vals;
            const res = await reqAddCategory(current.id, name);
            if (res.status === 0) {
                message.success('添加分类成功!');
                setVisible(visible => !visible);
                form.resetFields()
                refresh();
            } else {
                message.error(res.msg);
            }
        })
        .catch(() => {})
}

function cancel(form, setVisible) {
    form.resetFields();
    setVisible(visible => !visible)
}

function setTitle(current) {
    if (current) {
        return (
            <Fragment>
                在 [<LinkButton>{current.name}</LinkButton>] 下添加分类：
            </Fragment>
        )
    }
}